﻿using System;
using System.Net;
using System.IO;
using HtmlExtractor;
using System.Xml.Linq;
using System.Linq;
using System.Xml.Serialization;
using Reader.Domain;
using System.Runtime.Serialization;
using System.Xml;
using System.Text;
using System.Collections.Generic;
using SLHtmlExtractor.ObjectOutput;
using HtmlExtractor.Output;
using System.Text.RegularExpressions;
namespace Reader
{
    public enum FileType
    {
        None,
        Chapter,
        BookPage,
        Content
    }
    public static class SaveFile
    {
        public static string SaveImage(string uri, string imagePath,bool isCache,TimeSpan? cacheTime)
        {
            if (!File.Exists(imagePath))
            {

                WebClient client = new WebClient();
                client.OpenReadAsync(new Uri(uri));
                client.OpenReadCompleted += (s, args) =>
                {
                    if (args.Error == null)
                    {
                        if (args.Result.CanRead)
                        {
                            Byte[] buffer = new Byte[args.Result.Length];
                            args.Result.Read(buffer, 0, buffer.Length);
                            File.WriteAllBytes(imagePath, buffer);
                            if (isCache)
                                Cache.Current.Add(uri, imagePath, cacheTime.Value);
                        }
                    }
                };
            }
            else
            {
                //缓存
                if(isCache)
                    Cache.Current.Add(uri, imagePath, cacheTime.Value);
            }
            return imagePath;
        }
        public static XDocument GenerateXaml(string html, string uri, string template)
        {
            ParserContext context = new ParserContext(html, uri);
            Extractor extr = new Extractor(ReaderPath.XmlExtractorFile);
            PageResult result;
            extr.TryGetResult(context, out result);
            XDocumentOutput output = new XDocumentOutput();
            XDocument doc = XDocument.Load(template);
            output.Template = doc;
            XDocument rdoc;
            output.TryGetOutPutResult(result, out rdoc);
            return rdoc;
          
        }
        public static T GenerateObject<T>(string html, string uri) where T : new()
        {
            ParserContext context = new ParserContext(html, uri);
            Extractor extr = new Extractor(ReaderPath.ObjectExtractorFile);
            PageResult result;
            extr.TryGetResult(context, out result);
            T b = new T();
            ConvertToObject ct = new ConvertToObject();
            object o = b as object;
            ct.TryGetOutPutResult(result, ref o);
            return b;
        }
    }
   
}
